package mylab.base.foundation.orm;

import com.google.common.base.Preconditions;

import javax.sql.DataSource;

import cn.hutool.db.Db;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import mylab.base.foundation.orm.ability.DsAdmin;

@Slf4j
public class DbHelper implements DsAdmin {
    private static class SingletonHolder {
        static final DbHelper instance = new DbHelper();
    }

    public static DbHelper getInstance() {
        return DbHelper.SingletonHolder.instance;
    }

    @Getter
    @Setter
    DataSource dataSource;

    Db db;

    private DbHelper() {
    }

    public void init(DataSource dataSource) {
        this.dataSource = dataSource;
    }


    @Override
    public Db getDb() {
        if (db == null) {
            db = Db.use(getDataSource());
        }

        Preconditions.checkNotNull(db, "db is null");
        return db;
    }
}
